<template>
  <h1>预约管理</h1>
  <el-drawer v-model="drawer" title="I am the title" :with-header="false">
    <el-form :model="newAppointment">
      <el-form-item label="科室" :label-width="formLabelWidth">
        <el-select v-model="newAppointment.departmentId" placeholder="请选择科室" @change="fetchDoctors">
          <el-option v-for="department in departments" :key="department.id" :label="department.name" :value="department.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生" :label-width="formLabelWidth">
        <el-select v-model="newAppointment.doctorId" placeholder="请选择医生" @change="fetchSchedules">
          <el-option v-for="doctor in doctors" :key="doctor.userId" :label="doctor.name" :value="doctor.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" :label-width="formLabelWidth">
        <el-select v-model="newAppointment.scheduleId" placeholder="请选择预约时间">
          <el-option v-for="schedule in schedules" :key="schedule.scheduleId" :label="`${schedule.date} - ${schedule.time} (Room: ${schedule.roomId})`" :value="schedule.scheduleId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="newAppointment.description" type="textarea" placeholder="填写详细病情描述"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="drawer = false">取消</el-button>
      <el-button type="primary" @click="createAppointment">确定</el-button>
    </div>
  </el-drawer>

  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <div>
        <el-button type="primary" @click="drawer = true">新建预约</el-button>
        <el-button type="danger" @click="deleteAppointment" :disabled="!selectedAppointmentId">删除预约</el-button>
      </div>
    </div>
    <el-table :data="appointments" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="appointmentId" label="Appointment ID" width="180"></el-table-column>
      <el-table-column prop="patientName" label="Patient Name" width="120"></el-table-column>
      <el-table-column prop="doctorName" label="Doctor Name" width="120"></el-table-column>
      <el-table-column prop="appointmentTime" label="Appointment Time" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.appointmentTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="Status" width="100"></el-table-column>
      <el-table-column prop="description" label="Description"></el-table-column>
      <el-table-column prop="createdTime" label="Created Time" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdTime) }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios';
import { ElButton, ElInput, ElDialog, ElForm, ElFormItem, ElRadio, ElRadioGroup, ElMessage, ElDrawer, ElSelect, ElOption } from 'element-plus';

export default {
  components: {
    ElButton,
    ElInput,
    ElDialog,
    ElForm,
    ElFormItem,
    ElRadio,
    ElRadioGroup,
    ElDrawer,
    ElSelect,
    ElOption
  },
  name: 'AppointmentTable',
  data() {
    return {
      drawer: false,
      appointments: [],
      selectedAppointmentId: null,
      createDialogVisible: true,
      newAppointment: {
        departmentId: null,
        doctorId: null,
        scheduleId: null,
        description: ''
      },
      departments: [
        { id: 1, name: '内科' },
        { id: 2, name: '外科' },
        { id: 3, name: '儿科' },
        { id: 4, name: '妇产科' },
        { id: 5, name: '眼科' },
        { id: 6, name: '耳鼻喉科' },
        { id: 7, name: '皮肤科' },
        { id: 8, name: '精神科' },
        { id: 9, name: '骨科' },
        { id: 10, name: '急诊科' }
      ],
      doctors: [],
      schedules: [],
      formLabelWidth: '120px'
    };
  },
  methods: {
    formatDate(dateString) {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
      return new Date(dateString).toLocaleDateString(undefined, options);
    },
    handleSelectionChange(selection) {
      this.selectedAppointmentId = selection.length > 0 ? selection[0].appointmentId : null;
    },
    async fetchAppointments() {
      try {
        const response = await axios.get('http://localhost:8085/api/appointment/getByPatientId', {
          params: { id: 1 }
        });
        this.appointments = response.data;
      } catch (error) {
        ElMessage.error('获取预约列表失败');
      }
    },
    async fetchDoctors(departmentId) {
      try {
        const response = await axios.get(`http://localhost:8085/api/doctor/specialty/${departmentId}`);
        this.doctors = response.data.data;
      } catch (error) {
        ElMessage.error('获取医生列表失败');
      }
    },
    async fetchSchedules(doctorId) {
      try {
        const response = await axios.post('http://localhost:8085/schedule', {
          doctorId: doctorId,
          start: "",
          end: "",
          time: "",
          roomId: ""
        });
        this.schedules = response.data;
      } catch (error) {
        ElMessage.error('获取时间表失败');
      }
    },
    async createAppointment() {
      try {
        const response = await axios.post('http://localhost:8085/api/appointment/create', {
          patientId: this.$store.state.id,
          doctorId: this.newAppointment.doctorId,
          scheduleId: this.newAppointment.scheduleId,
          description: this.newAppointment.description
        });
        this.appointments.push(response.data);
        ElMessage.success('预约创建成功');
        this.createDialogVisible = false;
        await this.fetchAppointments();
      } catch (error) {
        ElMessage.error('预约创建失败');
      }
    },
    async deleteAppointment() {
      if (!this.selectedAppointmentId) {
        ElMessage.warning('请先选择一个预约');
        return;
      }

      try {
        await axios.delete('http://localhost:8085/api/appointment/delete', {
          params: { id: this.selectedAppointmentId }
        });
        this.appointments = this.appointments.filter(appointment => appointment.appointmentId !== this.selectedAppointmentId);
        ElMessage.success('预约删除成功');
      } catch (error) {
        ElMessage.error('预约删除失败');
      }
    }
  },
  mounted() {
    this.fetchAppointments();
  }
};
</script>

<style scoped>
</style>
